import {FlatList, StyleSheet, View} from 'react-native';
import {Empty, Header, ImgText4, ObserverView} from '../../components';
import {useTableReducer} from '../../hooks';
import {FeaturedRankList} from '../../services';
import {useCallback, useEffect} from 'react';
import {BindItem} from '../../mobx/home';
import {dpw12} from '../../constants';

const ViewMore = (props: any) => {
  const {navigation, route} = props;
  const {title, typeId} = route.params || {};
  const [{data, total, loading, pageIndex}, dispatch] = useTableReducer({
    total: 0,
    data: [],
    pageIndex: 1,
    pageSize: 10,
    loading: false,
  });

  const getData = useCallback(
    (idx: number, isMore?: boolean) => {
      if (typeId) {
        FeaturedRankList({
          Type: typeId,
          PageIndex: idx,
          PageSize: 10,
        })
          .then((res: any) => {
            if (!Array.isArray(res?.Data)) {
              dispatch({type: 'error'});
            } else {
              dispatch({
                type: 'success',
                payload: {
                  data: isMore
                    ? (preD: any[]) => [...preD, ...res.Data]
                    : res?.Data,
                  total: res?.Count,
                  pageIndex: idx,
                },
              });
            }
          })
          .catch(() => {
            dispatch({type: 'error'});
          });
      }
    },
    [typeId, dispatch],
  );

  // 获取列表数据
  useEffect(() => {
    getData(1);
  }, [getData]);

  // 加载更多
  const onLoadMore = () => {
    if (!loading && typeof total === 'number' && total > (data || []).length) {
      getData(pageIndex + 1, true);
    }
  };

  const _randDataItem = ({item}: {item: BindItem}) => {
    return <ImgText4 {...item} idx={typeId} navigation={navigation} />;
  };

  return (
    <ObserverView style={{flex: 1}} themeStyle={{backgroundColor: 'color_12'}}>
      <Header title={title} navigation={navigation} />
      <View style={styles.con}>
        {Array.isArray(data) && data.length > 0 ? (
          <FlatList
            style={{paddingVertical: dpw12}}
            data={data}
            renderItem={_randDataItem}
            keyExtractor={item => `${item.BID}`}
            onEndReachedThreshold={0.1}
            onEndReached={onLoadMore}
          />
        ) : (
          <Empty />
        )}
      </View>
    </ObserverView>
  );
};

export default ViewMore;

const styles = StyleSheet.create({
  con: {
    flex: 1,
  },
});
